package chaincode

import (
	"encoding/json"
	"fmt"

	"github.com/hyperledger/fabric-contract-api-go/contractapi"
)

// SmartContract provides functions for managing an Object
type SmartContract struct {
	contractapi.Contract
}

// Object describes basic details of what makes up a simple object
type Object struct {
	ID   string `json:"ID"`
	Hash string `json:"hash"`
}

// InitLedger adds a base set of objects to the ledger
func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
	objects := []Object{
		{ID: "object_0", Hash: "ec13a4c02aaa0ef53893742d5bf7d14c960333e0275a9c6472774e85c9f502c5"},
	}

	for _, object := range objects {
		objectJSON, err := json.Marshal(object)
		if err != nil {
			return err
		}

		err = ctx.GetStub().PutState(object.ID, objectJSON)
		if err != nil {
			return fmt.Errorf("failed to put to world state. %v", err)
		}
	}

	return nil
}

// CreateObject issues a new object to the world state with given details.
func (s *SmartContract) CreateObject(ctx contractapi.TransactionContextInterface, id string, hash string) error {
	exists, err := s.ObjectExists(ctx, id)
	if err != nil {
		return err
	}
	if exists {
		return fmt.Errorf("the object %s already exists", id)
	}

	object := Object{
		ID:   id,
		Hash: hash,
	}
	objectJSON, err := json.Marshal(object)
	if err != nil {
		return err
	}

	return ctx.GetStub().PutState(id, objectJSON)
}

// ReadObject returns the object stored in the world state with given id.
func (s *SmartContract) ReadObject(ctx contractapi.TransactionContextInterface, id string) (*Object, error) {
	objectJSON, err := ctx.GetStub().GetState(id)
	if err != nil {
		return nil, fmt.Errorf("failed to read from world state: %v", err)
	}
	if objectJSON == nil {
		return nil, fmt.Errorf("the object %s does not exist", id)
	}

	var object Object
	err = json.Unmarshal(objectJSON, &object)
	if err != nil {
		return nil, err
	}

	return &object, nil
}

// UpdateObject updates an existing object in the world state with provided parameters.
func (s *SmartContract) UpdateObject(ctx contractapi.TransactionContextInterface, id string, hash string) error {
	exists, err := s.ObjectExists(ctx, id)
	if err != nil {
		return err
	}
	if !exists {
		return fmt.Errorf("the object %s does not exist", id)
	}

	// overwriting original object with new object
	object := Object{
		ID:   id,
		Hash: hash,
	}
	objectJSON, err := json.Marshal(object)
	if err != nil {
		return err
	}

	return ctx.GetStub().PutState(id, objectJSON)
}

// DeleteObject deletes an given object from the world state.
func (s *SmartContract) DeleteObject(ctx contractapi.TransactionContextInterface, id string) error {
	exists, err := s.ObjectExists(ctx, id)
	if err != nil {
		return err
	}
	if !exists {
		return fmt.Errorf("the object %s does not exist", id)
	}

	return ctx.GetStub().DelState(id)
}

// ObjectExists returns true when object with given ID exists in world state
func (s *SmartContract) ObjectExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) {
	objectJSON, err := ctx.GetStub().GetState(id)
	if err != nil {
		return false, fmt.Errorf("failed to read from world state: %v", err)
	}

	return objectJSON != nil, nil
}

// GetAllObjects returns all objects found in world state
func (s *SmartContract) GetAllObjects(ctx contractapi.TransactionContextInterface) ([]*Object, error) {
	// range query with empty string for startKey and endKey does an
	// open-ended query of all objects in the chaincode namespace.
	resultsIterator, err := ctx.GetStub().GetStateByRange("", "")
	if err != nil {
		return nil, err
	}
	defer resultsIterator.Close()

	var objects []*Object
	for resultsIterator.HasNext() {
		queryResponse, err := resultsIterator.Next()
		if err != nil {
			return nil, err
		}

		var object Object
		err = json.Unmarshal(queryResponse.Value, &object)
		if err != nil {
			return nil, err
		}
		objects = append(objects, &object)
	}

	return objects, nil
}

// DeleteAllObjects returns delete all objects in world state
func (s *SmartContract) DeleteAllObjects(ctx contractapi.TransactionContextInterface) error {
	// range query with empty string for startKey and endKey does an
	// open-ended query of all objects in the chaincode namespace.
	resultsIterator, err := ctx.GetStub().GetStateByRange("", "")
	if err != nil {
		return err
	}
	defer resultsIterator.Close()

	for resultsIterator.HasNext() {
		queryResponse, err := resultsIterator.Next()
		if err != nil {
			return err
		}
		var object Object
		err = json.Unmarshal(queryResponse.Value, &object)
		if err != nil {
			return err
		}
		err = ctx.GetStub().DelState(object.ID)
		if err != nil {
			return err
		}
	}

	return nil
}
